package com.lzp.appexp.main

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.lzp.appexp.R


/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 1/6/21
 */
class TestService :Service(){
    private val TAG = "TestService"

    private var time = System.currentTimeMillis()

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val mManager = baseContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "test"
            val channel = NotificationChannel("test", name, NotificationManager.IMPORTANCE_LOW)
            mManager.createNotificationChannel(channel)
        }

        val builder = NotificationCompat.Builder(baseContext, "test")
        var mNotification = builder
                .setContentTitle("开始")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setOngoing(true)
                .setOnlyAlertOnce(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .build()
        mManager.notify(2, mNotification)
        startForeground(2,mNotification)

        Thread(Runnable {
            while (true){
                Thread.sleep(1000)
                builder.setContentTitle("${(System.currentTimeMillis()-time)/1000}")
                mNotification = builder.build()
                mManager.notify(2, mNotification)
            }
        }).start()
        return super.onStartCommand(intent, flags, startId)
    }
    override fun onBind(intent: Intent?): IBinder? {
        return mBinder
    }

    override fun onDestroy() {
        val mManager = baseContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "test"
            val channel = NotificationChannel("test", name, NotificationManager.IMPORTANCE_LOW)
            mManager.createNotificationChannel(channel)
        }

        val builder = NotificationCompat.Builder(baseContext, "test")
        val mNotification = builder
                .setContentTitle("结束了")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setOngoing(true)
                .setProgress(100, 0, false)
                .setOnlyAlertOnce(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .build()
        Thread.sleep(1000)
        mManager.notify(2, mNotification)
        super.onDestroy()
    }
    private val mBinder = LocalBinder()

    inner class LocalBinder:Binder(){
        fun getService():TestService{
            return this@TestService
        }
    }
}